/*
 *  txdnet.cn tonydon
 * 
 */
package cn.txdnet.txcms.service;

import cn.txdnet.txcms.domain.Catalogs;
import cn.txdnet.txcms.domain.CatalogsLevel;
import cn.txdnet.txcms.mapper.CatalogsLevelMapper;
import cn.txdnet.txcms.mapper.CatalogsMapper;
import cn.txdnet.txweb.basedao.mybatis.MybatisUtil;
import cn.txdnet.txweb.utils.CollectionUtil;
import cn.txdnet.txweb.utils.StringUtil;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.ibatis.session.SqlSession;
import txdnet.util.Logger;
import txdnet.util.StaticMark;

/**
 *
 * @author txdnet
 */
public class CatalogsLevelService {

    private static Class clazz = CatalogsLevelService.class;

    public static int deleteAll() {
        int num = 0;
        int size = 5;
        SqlSession sqlsn = MybatisUtil.getSqlSession(false);
        CatalogsLevelMapper catalogsLevelMapper = sqlsn.getMapper(CatalogsLevelMapper.class);
        try {
            while (true) {
                List<Integer> cidList = catalogsLevelMapper.selectCidList(size);
                if (CollectionUtil.isEmpty(cidList)) {
                    break;
                }
                int effectNum = catalogsLevelMapper.deleteCatalogsLevel(cidList);
                sqlsn.commit();
                num += effectNum;
                TimeUnit.MILLISECONDS.sleep(64);
            }
        } catch (Exception e) {
            sqlsn.rollback();
            Logger.error(clazz, e.toString().concat("-deleteAll()"));
        } finally {
            sqlsn.close();
        }
        return num;
    }

    /**
     * 重建类目级别表
     *
     * @return
     */
    public static int rebuildCatalogsLevel() {
        int num = 0;
        int size = 32;
        SqlSession sqlsn = MybatisUtil.getSqlSession(false);
        CatalogsMapper catalogsMapper = sqlsn.getMapper(CatalogsMapper.class);
        CatalogsLevelMapper catalogsLevelMapper = sqlsn.getMapper(CatalogsLevelMapper.class);
        Map<String, Integer> batchFactor = new HashMap<String, Integer>(2);
        batchFactor.put("listsize", size);
        String c = "c";
        try {
            for (int crow = 0; crow < 1024;) {
                batchFactor.put("crow", crow);
                List<Catalogs> list = catalogsMapper.queryBatchCatalogs(batchFactor);
                if (CollectionUtil.isEmpty(list)) {
                    break;
                }
                for (Catalogs ct : list) {
                    CatalogsLevel cl = new CatalogsLevel();
                    cl.setCid(ct.getCid());
                    int[] cidPathArr = getCidPathArray(ct.getCtp());
                    for (int k = 0; k < cidPathArr.length; k++) {
                        if (k >= 5) { //目前最多级别为5级
                            break;
                        }
                        Field f = CatalogsLevel.class.getDeclaredField(c.concat(Integer.toString(k + 1)));
                        f.setAccessible(true);
                        f.set(cl, cidPathArr[k]);
                    }
                    if (cl.validate() && catalogsLevelMapper.insertCatalogsLevel(cl) > 0) {
                        num++;
                    }
                }
                sqlsn.commit();
                crow += size;
                TimeUnit.MILLISECONDS.sleep(64);
            }
        } catch (Exception e) {
            sqlsn.rollback();
            Logger.error(clazz, e.toString().concat("-rebuildCatalogsLevel()"));
        } finally {
            sqlsn.close();
        }
        return num;
    }

    /**
     * 将CTP转为数组
     *
     * @param ctp
     * @return
     */
    public static int[] getCidPathArray(String ctp) {
        return StringUtil.parseArrStrToInt(
                StringUtil.split(ctp.substring(0, ctp.length() - 1), StaticMark.CHAR_LINE));
    }

    /**
     * 查询catalogs 类目级别
     *
     * @param ct
     * @return
     */
    public static int getLevelByCatalog(Catalogs ct) {
        if (ct == null) {
            return 0;
        }
        String ctp = ct.getCtp();
        if (StringUtil.isEmpty(ctp)) {
            return 0;
        }
        int[] cidPathArr = getCidPathArray(ctp);
        for (int level = 1; level <= cidPathArr.length; level++) {
            if (cidPathArr[level - 1] == ct.getCid().intValue()) {
                return level;
            }
        }
        return 0;
    }
    
    
    /**
     * 从分类路径中得到链接导航
     * @param ctp
     * @param navTpl eg: <a href="http://domain/list/$cid.shtm">$cname</a>&gt;
     * @return 
     */
    public static String getLevelNavigationByCtp(String ctp, String navTpl){
        if(StringUtil.isEmpty(ctp)){
            return StaticMark.STR_EMPTY;
        }
        // 如果只有顶级类目 如ctp= 123-
        int ctpLen = ctp.length();
        if(ctp.lastIndexOf(StaticMark.CHAR_LINE, ctpLen-2)<0){
            String catId = ctp.substring(0,ctpLen-1);
            Catalogs cat = CatalogsService.getCatalogsByCid(Integer.parseInt(catId));
            return (navTpl.replace("$cid", catId).replace("$cname", cat.getCname()));
        }
        int[] cidArray = getCidPathArray(ctp);
        if(CollectionUtil.arrayIsEmpty(cidArray)){
            return StaticMark.STR_EMPTY;
        }
        StringBuilder sb = new StringBuilder();
        for(int cid : cidArray){
            Catalogs cat = CatalogsService.getCatalogsByCid(cid);
            if(cat==null){
                break;
            }
            sb.append(navTpl.replace("$cid", Integer.toString(cid)).replace("$cname", cat.getCname()));
        }
        return sb.toString();
    }
}
